package com.jike.jkgame;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.jike.jkgame.data.ResourceType;
import com.jike.jkgame.data.UserResource;
import com.jike.jkgame.db.UserDAO;
import com.jike.jkgame.exception.EncodingException;
import com.jike.jkgame.exception.NetworkErrorException;
import com.jike.jkgame.network.MessageFactory;
import com.jike.jkgame.network.NetworkUtilis;
import com.jike.jkgame.network.ServerConfig;
import com.jike.jkgame.network.data.ResourceResultData;

import android.os.AsyncTask;

public class GetResourcesTask extends AsyncTask<ResourceType, Object, ResourceResultData>{
	@Override
	protected ResourceResultData doInBackground(ResourceType... params) {
		if (params == null || params.length <= 0) {
			return null;
		}
		JSONObject req = null;
		ResourceType type = params[0];
		String resKey = null;
		if (type == ResourceType.General) {
			req = MessageFactory.createGetGeneralsReqMessage();
			resKey = "generals";
		} else if (type == ResourceType.Weapon) {
			req = MessageFactory.createGetWeponsReqMessage();
			resKey = "weapons";
		} else if (type == ResourceType.Armor) {
			req = MessageFactory.createGetArmorsReqMessage();
			resKey = "armors";
		} else if (type == ResourceType.Mount) {
			req = MessageFactory.createGetMountsReqMessage();
			resKey = "mounts";
		} else if (type == ResourceType.Treasure) {
			req = MessageFactory.createGetTreasuresReqMessage();
			resKey = "treasures";
		} 
		
		ResourceResultData result = null;
		try {
			String response = NetworkUtilis.getHttpString(ServerConfig.get().getGameServer(), req);
			
			JSONObject json = new JSONObject(response);
			result = new ResourceResultData();
			result.opcode = json.optInt("opcode");
			
			if (result.opcode == 0) {
				UserDAO dao = UserDAO.get();
				JSONArray resObj = json.optJSONArray(resKey);
				if (resObj != null) {
					int size = resObj.length();
					UserResource[] res = new UserResource[size];
					for (int i=0; i<size; ++i) {
						JSONObject obj = resObj.getJSONObject(i);
						UserResource item = new UserResource();
						item.res = type;
						item.tid = obj.optInt("tid");
						item.sid = obj.optInt("sid");
						item.level = obj.optInt("level");
						item.exp = obj.optInt("exp");
						item.attack = obj.optInt("attack");
						item.defense = obj.optInt("defense");
						item.star = obj.optInt("star");
						item.cast = obj.optInt("cast");
						item.type = obj.optInt("type");
						item.add = obj.optInt("add");
						res[i] = item;
					}
					result.res = res;
				}
			}
		} catch (NetworkErrorException e) {
			e.printStackTrace();
		} catch (EncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

}
